// g++ -o whitelist_bypass.exe main.cpp -lshlwapi -ladvapi32
#include <iostream>
#include <windows.h>
#include <string>
#include <vector>
#include <shlobj.h>
#include <shlwapi.h>
#include <aclapi.h>
#include <sddl.h>

#pragma comment(lib, "shlwapi.lib")
#pragma comment(lib, "advapi32.lib")

// 常见的UAC白名单程序列表
std::vector<std::wstring> GetWhiteListedPrograms() {
    std::vector<std::wstring> programs;
    
    // Windows目录下的程序
    WCHAR windowsPath[MAX_PATH];
    GetWindowsDirectoryW(windowsPath, MAX_PATH);
    
    // 常见的白名单程序（这些程序通常有自动提升权限）
    programs.push_back(std::wstring(windowsPath) + L"\\System32\\ComputerDefaults.exe");
    programs.push_back(std::wstring(windowsPath) + L"\\System32\\fodhelper.exe");
    programs.push_back(std::wstring(windowsPath) + L"\\System32\\slui.exe");
    programs.push_back(std::wstring(windowsPath) + L"\\System32\\wsreset.exe");
    programs.push_back(std::wstring(windowsPath) + L"\\System32\\eventvwr.exe");  // 事件查看器
    programs.push_back(std::wstring(windowsPath) + L"\\System32\\compmgmt.msc");  // 计算机管理
    
    return programs;
}

// 检查文件是否存在
bool FileExists(const std::wstring& filePath) {
    DWORD attrib = GetFileAttributesW(filePath.c_str());
    return (attrib != INVALID_FILE_ATTRIBUTES && !(attrib & FILE_ATTRIBUTE_DIRECTORY));
}

// 检查当前进程是否具有管理员权限
BOOL IsElevated() {
    BOOL fRet = FALSE;
    HANDLE hToken = NULL;
    
    if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) {
        TOKEN_ELEVATION Elevation;
        DWORD cbSize = sizeof(TOKEN_ELEVATION);
        
        if (GetTokenInformation(hToken, TokenElevation, &Elevation, sizeof(Elevation), &cbSize)) {
            fRet = Elevation.TokenIsElevated;
        }
    }
    
    if (hToken) {
        CloseHandle(hToken);
    }
    
    return fRet;
}

// 检查进程是否在管理员完整性级别运行
bool IsRunningWithHighIntegrity() {
    HANDLE hToken;
    DWORD dwLengthNeeded;
    PTOKEN_MANDATORY_LABEL pTIL = NULL;
    DWORD dwIntegrityLevel;
    bool result = false;
    
    if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) {
        if (GetTokenInformation(hToken, TokenIntegrityLevel, NULL, 0, &dwLengthNeeded)) {
            pTIL = (PTOKEN_MANDATORY_LABEL)LocalAlloc(0, dwLengthNeeded);
            if (pTIL != NULL) {
                if (GetTokenInformation(hToken, TokenIntegrityLevel, pTIL, dwLengthNeeded, &dwLengthNeeded)) {
                    dwIntegrityLevel = *GetSidSubAuthority(pTIL->Label.Sid, 
                        (DWORD)(UCHAR)(*GetSidSubAuthorityCount(pTIL->Label.Sid)-1));
                    
                    // 高完整性级别 (0x00003000)
                    if (dwIntegrityLevel >= SECURITY_MANDATORY_HIGH_RID) {
                        result = true;
                    }
                }
                LocalFree(pTIL);
            }
        }
        CloseHandle(hToken);
    }
    
    return result;
}

// 尝试执行需要管理员权限的操作来验证权限
bool TestAdminPrivileges() {
    // 尝试打开需要管理员权限的注册表键
    HKEY hKey;
    LONG lResult = RegOpenKeyExW(HKEY_LOCAL_MACHINE, 
        L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion", 
        0, KEY_ALL_ACCESS, &hKey);
    
    if (lResult == ERROR_SUCCESS) {
        RegCloseKey(hKey);
        return true;
    }
    
    // 尝试创建系统目录下的文件（需要管理员权限）
    WCHAR tempPath[MAX_PATH];
    GetTempPathW(MAX_PATH, tempPath);
    
    std::wstring testFile = std::wstring(tempPath) + L"uac_test_" + std::to_wstring(GetCurrentProcessId()) + L".tmp";
    
    HANDLE hFile = CreateFileW(testFile.c_str(), GENERIC_WRITE, 0, NULL, 
        CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, NULL);
    
    if (hFile != INVALID_HANDLE_VALUE) {
        CloseHandle(hFile);
        DeleteFileW(testFile.c_str());
        return true;
    }
    
    return false;
}

// 检查UAC是否启用
bool IsUACEnabled() {
    HKEY hKey;
    DWORD dwUACEnabled = 1;
    DWORD dwSize = sizeof(DWORD);
    
    if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, 
        L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", 
        0, KEY_READ, &hKey) == ERROR_SUCCESS) {
        
        RegQueryValueExW(hKey, L"EnableLUA", NULL, NULL, 
            (LPBYTE)&dwUACEnabled, &dwSize);
        RegCloseKey(hKey);
    }
    
    return (dwUACEnabled != 0);
}

// 详细的权限验证报告
void PrintPrivilegeReport() {
    std::wcout << L"\n=== Privilege Verification Report ===" << std::endl;
    
    // 检查管理员权限
    BOOL isElevated = IsElevated();
    std::wcout << L"Administrator Privilege Detection: " << (isElevated ? L"[Yes]" : L"[No]") << std::endl;
    
    // 检查完整性级别
    bool isHighIntegrity = IsRunningWithHighIntegrity();
    std::wcout << L"High Integrity Level: " << (isHighIntegrity ? L"[Yes]" : L"[No]") << std::endl;
    
    // 测试实际权限
    bool hasAdminPrivileges = TestAdminPrivileges();
    std::wcout << L"Actual Administrator Privileges: " << (hasAdminPrivileges ? L"[Yes]" : L"[No]") << std::endl;
    
    // 检查UAC状态
    bool uacEnabled = IsUACEnabled();
    std::wcout << L"UAC Status: " << (uacEnabled ? L"[Enabled]" : L"[Disabled]") << std::endl;
    
    // 综合判断
    if (isElevated && isHighIntegrity && hasAdminPrivileges) {
        std::wcout << L"\n[Success] UAC Bypass Verification: Complete success!" << std::endl;
        std::wcout << L"Current process has full administrator privileges" << std::endl;
    } else if (isElevated || hasAdminPrivileges) {
        std::wcout << L"\n[Partial Success] UAC Bypass Verification: Partial success" << std::endl;
        std::wcout << L"Current process has partial administrator privileges" << std::endl;
    } else {
        std::wcout << L"\n[Failure] UAC Bypass Verification: Not successful" << std::endl;
        std::wcout << L"Current process has no administrator privileges" << std::endl;
    }
}

// 使用白名单程序进行UAC绕过（简化版本）
bool BypassUACWithWhiteListedProgram(const std::wstring& programPath) {
    // 直接使用ShellExecute请求管理员权限
    HINSTANCE result = ShellExecuteW(
        NULL,                   // 父窗口句柄
        L"runas",               // 操作（请求管理员权限）
        programPath.c_str(),    // 程序路径
        L"",                    // 参数
        NULL,                   // 工作目录
        SW_HIDE                 // 显示方式
    );
    
    return reinterpret_cast<INT_PTR>(result) > 32;  // ShellExecute成功返回大于32的值
}

// 启动管理员权限的程序（带验证功能）
bool LaunchElevatedProgramWithVerification(const std::wstring& programPath) {
    std::wstring commandLine = L"";
    
    // 如果是cmd.exe，添加验证命令
    if (programPath.find(L"cmd.exe") != std::wstring::npos) {
        commandLine = L"/k echo [管理员权限已获取] && whoami && echo 正在验证UAC绕过状态... && echo.";
    }
    
    HINSTANCE result = ShellExecuteW(
        NULL,
        L"runas",
        programPath.c_str(),
        commandLine.c_str(),
        NULL,
        SW_SHOWNORMAL
    );
    
    if (reinterpret_cast<INT_PTR>(result) > 32) {
        // 等待程序启动
        Sleep(3000);
        
        // 在当前进程中显示详细的权限验证报告
        PrintPrivilegeReport();
        
        return true;
    }
    
    return false;
}

// 简单的管理员程序启动（不带验证）
bool LaunchElevatedProgram(const std::wstring& programPath) {
    std::wstring commandLine = L"";
    
    // 如果是cmd.exe，添加提示信息
    if (programPath.find(L"cmd.exe") != std::wstring::npos) {
        commandLine = L"/k echo [管理员权限已获取] && whoami && echo.";
    }
    
    HINSTANCE result = ShellExecuteW(
        NULL,
        L"runas",
        programPath.c_str(),
        commandLine.c_str(),
        NULL,
        SW_SHOWNORMAL
    );
    
    return reinterpret_cast<INT_PTR>(result) > 32;
}

// 显示使用帮助
void ShowUsage() {
    std::cout << "使用方法:" << std::endl;
    std::cout << "  uac_bypass.exe                    - 默认启动cmd.exe" << std::endl;
    std::cout << "  uac_bypass.exe <程序路径>         - 启动指定的程序" << std::endl;
    std::cout << "  uac_bypass.exe cmd.exe            - 启动cmd.exe（默认）" << std::endl;
    std::cout << "  uac_bypass.exe powershell.exe     - 启动PowerShell" << std::endl;
    std::cout << "  uac_bypass.exe notepad.exe        - 启动记事本" << std::endl;
    std::cout << "  uac_bypass.exe regedit.exe        - 启动注册表编辑器" << std::endl;
    std::cout << "  uac_bypass.exe compmgmt.msc       - 启动计算机管理" << std::endl;
    std::cout << "  uac_bypass.exe control.exe         - 启动控制面板" << std::endl;
    std::cout << "\n示例:" << std::endl;
    std::cout << "  uac_bypass.exe powershell.exe     - 以管理员权限启动PowerShell" << std::endl;
    std::cout << "  uac_bypass.exe C:\\Program Files\\MyApp\\myapp.exe - 启动自定义程序" << std::endl;
}

// 主函数
int main(int argc, char* argv[]) {
    // 设置控制台编码为UTF-8
    system("chcp 65001 > nul");
    
    // 默认启动的程序
    std::wstring targetProgram = L"cmd.exe";
    
    // 解析命令行参数
    if (argc > 1) {
        // 首先检查帮助参数（使用ANSI字符串比较）
        std::string arg = argv[1];
        if (arg == "-h" || arg == "--help" || arg == "/?") {
            ShowUsage();
            std::cout << "Press any key to exit..." << std::endl;
            getchar();
            return 0;
        }
        
        // 如果不是帮助参数，则转换为宽字符串并设置目标程序
        int size_needed = MultiByteToWideChar(CP_ACP, 0, argv[1], -1, NULL, 0);
        std::wstring programArg(size_needed, 0);
        MultiByteToWideChar(CP_ACP, 0, argv[1], -1, &programArg[0], size_needed);
        
        targetProgram = programArg;
    }
    
    std::wcout << L"=== UAC Whitelist Program Detection Tool (with verification) ===" << std::endl;
    std::wcout << L"Target Program: " << targetProgram << std::endl;
    std::wcout << L"Checking system status..." << std::endl;
    
    // 首先显示当前权限状态
    PrintPrivilegeReport();
    
    // 检查当前权限
    if (IsElevated()) {
        std::wcout << L"\n[Info] Current process already has administrator privileges" << std::endl;
        std::wcout << L"Launching administrator program with verification..." << std::endl;
        
        if (LaunchElevatedProgramWithVerification(targetProgram)) {
            std::wcout << L"[Success] Administrator program launched and verified" << std::endl;
        } else {
            std::wcout << L"[Error] Unable to launch administrator program" << std::endl;
        }
        
        return 0;
    }
    
    std::wcout << L"\n[Info] Current process has no administrator privileges, starting UAC whitelist program detection..." << std::endl;
    
    // 获取白名单程序列表
    auto programs = GetWhiteListedPrograms();
    std::vector<std::wstring> availablePrograms;
    
    // 检查哪些程序存在
    for (const auto& program : programs) {
        if (FileExists(program)) {
            availablePrograms.push_back(program);
            std::wcout << L"[Found] " << program << std::endl;
        }
    }
    
    if (availablePrograms.empty()) {
        std::wcout << L"[Error] No available UAC whitelist programs found" << std::endl;
        std::wcout << L"Attempting to directly request administrator privileges..." << std::endl;
        
        if (LaunchElevatedProgramWithVerification(targetProgram)) {
            std::wcout << L"[Success] Administrator privileges obtained through direct request" << std::endl;
        } else {
            std::wcout << L"[Error] All methods failed" << std::endl;
            return -1;
        }
        
        return 0;
    }
    
    std::wcout << L"\n[Info] Found " << availablePrograms.size() << L" available whitelist programs" << std::endl;
    std::wcout << L"Starting UAC bypass attempt..." << std::endl;
    
    // 尝试使用可用的白名单程序
    bool bypassSuccess = false;
    for (const auto& program : availablePrograms) {
        std::wcout << L"Attempting with: " << program << std::endl;
        
        if (BypassUACWithWhiteListedProgram(program)) {
            std::wcout << L"[Success] UAC bypass attempt sent" << std::endl;
            std::wcout << L"Waiting 3 seconds before launching administrator program with verification..." << std::endl;
            bypassSuccess = true;
            
            // 给程序一些时间启动
            Sleep(3000);
            
            if (LaunchElevatedProgramWithVerification(targetProgram)) {
                std::wcout << L"[Success] Administrator program launched and verified" << std::endl;
            } else {
                std::wcout << L"[Warning] Administrator program launch may have failed" << std::endl;
            }
            
            break;
        } else {
            std::wcout << L"[Failure] Bypass failed, trying next program..." << std::endl;
        }
    }
    
    if (!bypassSuccess) {
        std::wcout << L"[Error] All UAC bypass attempts failed" << std::endl;
        std::wcout << L"Attempting to directly request administrator privileges..." << std::endl;
        
        if (LaunchElevatedProgramWithVerification(targetProgram)) {
            std::wcout << L"[Success] Administrator privileges obtained through direct request" << std::endl;
        } else {
            std::wcout << L"[Error] All methods failed" << std::endl;
            return -1;
        }
    }
    
    std::wcout << L"\nProgram execution completed" << std::endl;
    std::wcout << L"Press any key to exit..." << std::endl;
    getchar();
    
    return 0;
}